import HeaderView from "@/component/Header"
import TimeOut from "@/component/TimeOut"
import TabbarView from "@/component/Tabbar"
import { useEffect, useState } from "react"
import style from './index.module.scss'
import { GetList, UpdateNum, CheckedCart, ProductRemove } from '@/api/shopcart'
import { Button, Checkbox, Image, Stepper, Toast, SwipeAction } from "antd-mobile"
import { shopcartType } from "@/type/shopcart"
import { useActivate } from "react-activation"
import { getCookie } from "@/utils"
import { useDispatch } from 'react-redux'
import { saveProductNum } from '@/reduxToolkit/reducers/productNum'

const Shopcart = () => {
  type CheckboxValue = string | number
  const dispatch = useDispatch()
  const [flag, setFlag] = useState(false) // 错误提示      
  const [shopcartList, setShopcartList] = useState<any>([]) // 购物车列表
  const [total, setTotal] = useState(0) // 总价
  const [radioValueID, setRadioValueID] = useState<any>([]) // 选中产品的ID
  const [checkAll, setCheckAll] = useState(false) // 是否全选
  const [numProduct, setNumProduct] = useState(0) // 购物车数量

  // 总价
  const totalPrice = (data: any, value: any) => {
    let sum = 0
    data.filter((item: {id: number}) => value.includes(item.id)).forEach((itemB: {goods: {price: number}, num: number}) => {
      return sum += itemB.goods.price * itemB.num
    })
    setTotal(sum)
  }

  // 数据初始化
  const init = async () => {
    const res = await GetList('include=goods').catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setFlag(true)
    })

    try {
      setNumProduct(res?.data.data.length)
      setShopcartList(res?.data.data)  
      const checkRadioID = res?.data.data.filter((item: {is_checked: number}) => item.is_checked === 1).map((itemB: {id: number}) => itemB.id)
      setRadioValueID(checkRadioID) // 选中产品ID的集合
      totalPrice(res?.data.data, checkRadioID)
      if(res?.data.data.length === checkRadioID.length) { // 设置全选状态
        setCheckAll(true)
      }
    } catch (error) {
      console.log(error)  
    }
  }
  useEffect(() => { init() }, [])

  // 数量修改
  const numChange = async (num: number, id: number) => {
    const res = await UpdateNum(id, {num: num}).catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
        Toast.show({icon: 'fail', content: '请稍后再试', duration: 1500, maskClickable: false})
      }
    })

    try {
      if(res?.status === 204) {
        // 找出修改数量对应产品的ID 然后在将这个产品的数量进行修改
        shopcartList.filter((item: any) => item.id === id)[0].num = num
        totalPrice(shopcartList, radioValueID)
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 删除产品
  const deleteProduct = async (id: number) => {
    const res = await ProductRemove(id).catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
        Toast.show({icon: 'fail', content: '请稍后再试', duration: 1500, maskClickable: false})
      }
    })
    const res2= await GetList('include=goods')
    try {
      if(res?.status === 204) {
        dispatch(saveProductNum(res2.data.data.length))
        Toast.show({icon: 'success', content: '删除成功', duration: 500, maskClickable: false, afterClose: () => {
          // init()
          const list = shopcartList.filter((item: {id: number}) => item.id !== id)
          setShopcartList(list) // 更新购物列表
          const ID = radioValueID.filter((item: number) => item !== id)
          setRadioValueID(ID) // 更新 选中产品的ID
          totalPrice(list, ID) 
          if(list.length === ID.length) { // 如果购物车商品数量 和 更新选中的商品的数量一致 则是全选
            setCheckAll(true)
          }
        }})
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 购物车数据
  const getCartList = () => {
    return shopcartList.map((item: shopcartType) => {
       return (
         <SwipeAction rightActions={[{ key: 'delete', text: '删除',color: 'danger', onClick: ()=> deleteProduct(item.id)}]} key={item.id}>
          <div className={style.item} key={item.id}>
            <div className={style.itemLeft}>
              <div className={style.radio}><Checkbox value={item.id}/></div>
              <div className={style.img}><Image width={80} height={80} src={item.goods.cover_url}/></div>
              <div className={style.msg}>
                <p className={style.title}>{item.goods.title}</p>
                <p>￥{item.goods.price}</p>
              </div>
            </div> 
            <div className={style.itemRight}>
              <div className={style.itemRightBox}>
                 <p className={style.stock}>库存: 100</p>
                 <Stepper className={style.stepper} min={1} defaultValue={item.num} max={item.goods.stock} step={1} onChange={(value) => numChange(value, item.id)}/>
              </div>
            </div> 
          </div>
         </SwipeAction> 
       )
    })
  }

  // 选中 或 取消 购物车产品
  const radioCheck = async (value: CheckboxValue[]) => {
    setRadioValueID(value)
    if(shopcartList.length === value.length && setShopcartList.length !== 0 && value.length !== 0) {
      setCheckAll(true)
    } else {
      setCheckAll(false)
    }
    totalPrice(shopcartList, value)
    await CheckedCart({cart_ids: value}).catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
        Toast.show({icon: 'fail', content: '请稍后再试', duration: 1500, maskClickable: false})
      }
    })
  }

  // 全选 或 全不选 公共信息
  const checkAllPublicMsg = async (id: number[], flag: boolean) => {
    setRadioValueID(id)
    setCheckAll(flag)
    await CheckedCart({cart_ids: id}).catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
        Toast.show({icon: 'fail', content: '请稍后再试', duration: 1500, maskClickable: false})
      }
    })
  }

  // 全选 或 全不选
  const getCheckAll = async (flag: boolean) => {
    if(flag) {
      const ID = shopcartList.map((item: {id: number}) => item.id)
      totalPrice(shopcartList, ID)
      checkAllPublicMsg(ID, true)
    } else {
      setTotal(0)
      checkAllPublicMsg([], false)
    }
  }

  // 激活缓存 cookie的数量 和 init的初始化的数量 不同 说明新增了产品 需要重新刷新
  useActivate(() => {
    if(numProduct !== getCookie('productNum')) {
      init()
    }
  })

  return (
    <>
      {/* 头部信息 */}
      <HeaderView title="购物车" backIcon={false}/>

      {
        shopcartList.length !== 0
        ?
        <>
        <div className={style.shopcartBox}> 
          <Checkbox.Group value={radioValueID} onChange={(value: CheckboxValue[]) => radioCheck(value)}>{getCartList()}</Checkbox.Group>
        </div> 

        {/* 结算 */}
        <div className={style.pay}>
          <Checkbox checked={checkAll} onChange={((flag) => getCheckAll(flag))}></Checkbox>
          <div className={style.payRight}>
            <span>￥{total}</span>
            <Button size="small" color="danger">结算</Button>
          </div>
        </div>

        {/* tabbar信息 */}
        <TabbarView/>
        </>
        :
        <p>购物车空空如也~</p>
      }

      {/* 错误提示页面 */}
      {flag && <TimeOut/>}
    </>
  )
}

export default Shopcart